package com.expense.app.admin.services.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.expense.app.admin.common.BaseService;
import com.expense.app.admin.model.dto.adminUser.AdminUserDetailDTO;
import com.expense.app.admin.model.dto.adminUser.AdminUserGeneratePasswordDTO;
import com.expense.app.admin.model.dto.adminUser.AdminUserListDTO;
import com.expense.app.admin.model.params.adminUser.AdminUserDetailSaveParam;
import com.expense.app.admin.model.params.adminUser.AdminUserListParam;
import com.expense.app.admin.model.params.adminUser.AdminUserModifyPasswordParam;
import com.expense.app.admin.services.AdminUserServ;
import com.expense.common.constant.enums.DeletedStatus;
import com.expense.common.dao.auth.AdminUserDao;
import com.expense.common.dao.auth.AdminUserRoleDao;
import com.expense.common.entity.params.CheckParam;
import com.expense.common.entity.params.DetailParam;
import com.expense.common.exception.PlatformException;
import com.expense.common.model.auth.AdminUser;
import com.expense.common.model.auth.AdminUserRole;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdminUserServImpl extends BaseService implements AdminUserServ {
    private static final Log log = LogFactory.get();

    @Autowired
    AdminUserDao adminUserDao;

    @Autowired
    AdminUserRoleDao adminUserRoleDao;

    @Override
    public AdminUserListDTO findAllEmployeeList() {
        List<AdminUser> list = adminUserDao.findAllEmployeeList();
        Long total = list!=null?Long.valueOf(list.size()):0l;
        return new AdminUserListDTO(list,total);
    }
    @Override
    public AdminUserListDTO findList(AdminUserListParam param) {
        Map<String,Object> condition = new HashMap<>();
        condition.put("key",param.getKey());
        condition.put("enable",param.getIsEnable());
        condition.put("departmentId",param.getDeptId());
        PageQuery pageQuery = initPageQuery(param.getPage(),param.getSort());
        pageQuery.setParas(condition);
        adminUserDao.findListPage(pageQuery);
        return new AdminUserListDTO(pageQuery.getList(),pageQuery.getTotalRow());
    }

    @Override
    public AdminUserDetailDTO findDetail(DetailParam param) {
        Long id = Convert.toLong(param.getId(),0l);
        if(id <= 0) throw new PlatformException("没有查询到用户信息");
        AdminUser adminUser = adminUserDao.findDetail(id);
        List<Long> roleIds = adminUserRoleDao.findRoleIdByUserId(adminUser.getId());
        adminUser.setRoleIds(roleIds);
        return new AdminUserDetailDTO(adminUser);
    }

    @Override
    @CachePut(cacheNames = "adminUser",value = "adminUser",key = "#param.adminUser.id")
    public AdminUser saveOne(AdminUserDetailSaveParam param) {
        AdminUser adminUser = param.getAdminUser();
        List<Long> roleIds = param.getRoleIds();
        setBaseInfo(adminUser);
        if(Convert.toLong(adminUser.getId(),0l) <= 0) {
            adminUser.setPassword(SecureUtil.md5("111111")); //默认密码 "111111"
            adminUserDao.insertTemplate(adminUser,true);
        } else {
            adminUserDao.updateTemplateById(adminUser);
            adminUserRoleDao.deleteByUserId(adminUser.getId(),getCurrentUser().getId());
        }
        List<AdminUserRole> adminUserRoleList = new ArrayList<>();
        if(roleIds!=null && roleIds.size()>0){
            for(Long roleId : roleIds){
                AdminUserRole userRole = new AdminUserRole();
                userRole.setAdminUserId(adminUser.getId());
                userRole.setAdminRoleId(roleId);
                setBaseInfo(userRole);
                adminUserRoleList.add(userRole);
            }
            adminUserRoleDao.insertBatch(adminUserRoleList);
        }
        return adminUser;
    }

    /**
     * 验证 登录名是否已经存在
     * @param checkParam
     * @return
     */
    @Override
    public Boolean checkByUserName(CheckParam checkParam){
        if(checkParam.getKey() == null) throw new PlatformException("请提交登录名");
        AdminUser adminUser;
        if(checkParam.getId()!= null && checkParam.getId() > 0){
            adminUser = adminUserDao.findByIdAndDeleted(checkParam.getId());
            if(adminUser.getUsername().equals(checkParam.getKey())) return  true ;
        }
         adminUser = adminUserDao.findByUserName(checkParam.getKey());
        if(adminUser == null) return true ;
        return false;
    }

    @Override
    @CachePut(cacheNames = "adminUser",value = "adminUser",key = "#param.adminUser.id")
    public AdminUser savePassword(AdminUserModifyPasswordParam param) {
        AdminUser adminUser = param.getAdminUser();
        if(adminUser== null) throw new PlatformException("用户不存在");
        setBaseInfo(adminUser);
        adminUser.setPassword(SecureUtil.md5(param.getPassword()));
        adminUserDao.updateTemplateById(adminUser);
        return adminUser;
    }

    @Override
    public AdminUserGeneratePasswordDTO generatePassword(DetailParam param) {
        Long id = Convert.toLong(param.getId(),0l);
        if(id <=0 ) throw new PlatformException("用户不存在");
        AdminUser adminUser = new AdminUser();
        adminUser.setId(id);
        String password =  RandomUtil.randomString(8);
        setBaseInfo(adminUser);
        adminUser.setPassword(SecureUtil.md5(password));
        adminUserDao.updateTemplateById(adminUser);
        return new AdminUserGeneratePasswordDTO(password);
    }

    @Override
    public AdminUser resetPassword(Long id) {
        AdminUser adminUser = adminUserDao.findByIdAndDeleted(id);
        if(adminUser == null) throw new PlatformException("用户已不存在");
        setBaseInfo(adminUser);
        adminUser.setPassword(SecureUtil.md5("111111"));
        adminUserDao.updateTemplateById(adminUser);
        return adminUser;
    }

    @Override
    public Long deleteOne(DetailParam param) {
        Long id = Convert.toLong(param.getId(),0l);
        if(id <= 0) throw new PlatformException("请选择删除的用户");
        AdminUser adminUser = adminUserDao.findByIdAndDeleted(id);
        if(adminUser == null) throw new PlatformException("用户已不存在");
        adminUser.setDeleted(DeletedStatus.DELETED);
        setBaseInfo(adminUser);
        adminUserDao.updateTemplateById(adminUser);
//        adminUserRoleDao.deleteByUserId(id,getCurrentUser().getId());
        return id;
    }

    @Override
    public Long isEnableOne(DetailParam param) {
        Long id = Convert.toLong(param.getId(),0l);
        if(id <= 0) throw new PlatformException("请选择禁用的用户");
        AdminUser adminUser = adminUserDao.findByIdAndDeleted(id);
        if(adminUser == null) throw new PlatformException("用户已不存在");
        setBaseInfo(adminUser);
        adminUser.setIsEnable(param.getIsEnable());
        adminUserDao.updateTemplateById(adminUser);
        return id;
    }

    @Override
    @Cacheable(cacheNames = "adminUser",value = "adminUser",key = "#id")
    public AdminUser getAdminUser(Long id) {
        log.info("---- 没有缓存，读取数据库 ---------");
        return adminUserDao.findByIdAndDeleted(id);
    }


}
